<?php
class ModelLekoService extends Model
{
    const WSDL_URL=LEKO_WSDL;
    public $vendors, $error, $searchNum, $id, $articles, $vendor, $cost, $alts, $notOriginals, $uid, $orderNum;
    protected $params, $methodName, $lastAddedId;
    protected $properties=array(
        'Article',
        'Name',
        'Cost',
        'Duration',
        'Amount',
        'Description',
        'VendorName',
    );

    public function getArticles($num, $vendor)
    {
        $num=strtoupper($num);
        $num=str_replace(' ','',$num);
        $num=str_replace('-','',$num);

        $this->searchNum=$num;
        $this->vendor=$vendor;
        $result=new self(null);
        if($articles=$this->getArts()){
            if($result->vendors=$this->model->load('manufacturerModel')->getVendors($articles)) return $result;
            $result->articles=$this->articles=$articles;
            foreach($articles as $num=>$art){
                if($art->Amount<=0) $result->articles[$num]->Amount='';
                if($alts=$this->getAlts($art->Id, $art->SearchId)){
                    foreach($alts as $alt){
                        if($alt){
                            if($alt->Amount<=0) $alt->Amount='';
                            $result->alts[]=$alt;
                        }
                    }
                }
                if($notOriginals=$this->getNotOriginals($art->Id, $art->SearchId)){
                    foreach($notOriginals as $notOriginal){
                        if($notOriginal){
                            if($notOriginal->Amount<=0) $notOriginal->Amount='';
                            $result->notOriginals[]=$notOriginal;
                        }
                    }
                }
            }
        }

        $result->error=$this->error;

        return $result;
    }

    public function getHtmlArticles($articles)
    {
        $this->load->language('module/lekoService');

        $html='';

        if($arts=$articles->articles) $html.='<h2>'.$this->language->get('articles_title').'</h2>'.$this->getHtmlTable($arts);
        if($alts=$articles->alts) $html.='<h2>'.$this->language->get('alts_title').'</h2>'.$this->getHtmlTable($alts);
        if($notOriginals=$articles->notOriginals) $html.='<h2>'.$this->language->get('notOriginals_title').'</h2>'.$this->getHtmlTable($notOriginals);

        if($arts || $alts || $notOriginals){
            $this->load->helper('html');
            $html.=getAjaxButton(array(
                'button_text'=>$this->language->get('button_cart'),
                'div_class'=>'button',
                'span_id'=>'add-to-cart',
                'span_class'=>'button',
            ));

            $html.=getLoadingImage(array(
                'img_src'=>HTTP_IMAGE.'data/loadingIcon.gif',
                'div_id'=>'to-cart-loading',
                'div_class'=>'loading',
                'img_id'=>'loading',
            ));
        }

        return $html;
    }

    public function getHtmlVendors($vendors)
    {
        if(!$vendors || sizeof($vendors)<2) return false;

        $html='';
        foreach($vendors as $vendor){
            $html.='<p><a class="vendors" href="" name="'.$vendor->name.'" onclick="return false;">'.$vendor->name.'</a></p>';
        }

        return $html;
    }

    protected function getArts()
    {
        $model=$products=$this->model->load('productModel');

        $vendorId=0;
        if($this->vendor && $vendor=$this->model->load('manufacturerModel')->findByAttributes(array('name'=>$this->vendor))) $vendorId=$vendor['manufacturer_id'];

        $params=$vendorId ? array('sku'=>$this->searchNum, 'manufacturer_id'=>$vendorId) : array('sku'=>$this->searchNum);

        if($products=$model->getProducts($params)){
            $arts=$this->checkProducts($products, 'arts');
        }else{
            if($arts=$this->getSoap()){
                foreach($arts as $num=>$art){
                    $arts[$num]->Id=$this->save($art);
                }
            }
        }

        return $arts;
    }

    protected function getAlts($localId, $remoteId)
    {
        if($products=$this->model->load('productAltsModel')->getProducts($localId)){
            $alts=$this->checkProducts($products, 'alts');
        }elseif($alts=$this->findById($remoteId, 'alts')){
            foreach($alts as $num=>$alt){
                $alts[$num]->Id=$this->save($alt, 'alts');
                $alts[$num]->Duration=$this->model->load('productModel')->getStatusText($alt->Amount, $alt->Duration);
            }
        }

        return $alts;
    }

    protected function getNotOriginals($localId, $remoteId)
    {
        if($products=$this->model->load('productNotOriginalsModel')->getProducts($localId)){
            $notOriginals=$this->checkProducts($products, 'notOriginal');
        }elseif($notOriginals=$this->findById($remoteId, 'notOriginal')){
            foreach($notOriginals as $num=>$notOriginal){
                $notOriginals[$num]->Id=$this->save($notOriginal, 'notOriginal');
                $notOriginals[$num]->Duration=$this->model->load('productModel')->getStatusText($notOriginal->Amount, $notOriginal->Duration);
            }
        }

        return $notOriginals;
    }

    protected function save($product=false, $name='')
    {
        if(!$product) return false;

        $model=$this->model->load('productModel');
        $categoryId=$model->getCategoryId($product);

        $newProduct=array(
            'product_description'=>$model->createProdDescription($product),
            'product_wholesale_id'=>$product->Id,
            'warehouse'=>isset($product->Warehouse) ? $product->Warehouse : 0,
            'SupplierRef'=>isset($product->SupplierRef) ? $product->SupplierRef : 0,
            'ReplacementId'=>isset($product->ReplacementId) ? $product->ReplacementId : 0,
            'WhQuantity'=>isset($product->WhQuantity) ? $product->WhQuantity : 0,
            'model'=>$product->Article,
            'sku'=>$product->Article,
            'upc'=>'',
            'ean'=>'',
            'jan'=>'',
            'isbn'=>'',
            'mpn'=>'',
            'location'=>'',
            'price'=>$product->Cost,
            'tax_class_id'=>'',
            'quantity'=>$product->Amount,
            'minimum'=>1,
            'subtract'=>1,
            'stock_status_id'=>$product->Duration,
            'shipping'=>1,
            'keyword'=>$this->model->load('seoModel')->createSeoWord($product->Name),
            'image'=>'',
            'date_modified'=>date('Y-m-d'),
            'date_available'=>'',
            'timer'=>time(),
            'length'=>'',
            'width'=>'',
            'height'=>'',
            'length_class_id'=>1,
            'weight'=>'',
            'weight_class_id'=>1,
            'status'=>1,
            'sort_order'=>1,
            'manufacturer_id'=>$model->getManufacturerId($product),
            'main_category_id'=>$categoryId,
            'product_category'=>array($categoryId),
            'product_store'=>array(0),
            'related'=>'',
            'option'=>'',
            'points'=>'',
            'product_reward'=>array(1=>array('points'=>'')),
            'product_layout'=>array(array('layout_id'=>'')),
        );

        $this->load->model('catalog/product');

        if($id=$this->model_catalog_product->addProduct($newProduct)){
            if($name=='alts' && isset($this->lastAddedId)){
                $this->model->load('productAltsModel')->save(array('alt_id'=>$id,'product_id'=>$this->lastAddedId));
            }elseif($name=='notOriginal' && isset($this->lastAddedId)){
                $this->model->load('productNotOriginalsModel')->save(array('not_original_id'=>$id,'product_id'=>$this->lastAddedId));
            }else{
                $this->lastAddedId=$id;
            }
            return $id;
        }

        return false;
    }

    private function checkProducts($products,$check)
    {
        $productsToUpdate=array();
        foreach($products as $product){
            if($product && time()-$product->Timer>$this->config->get('config_price_update_limit')) $productsToUpdate[]=$product;
        }

        return $productsToUpdate ? $this->updateProducts($productsToUpdate, $check) : $products;
    }

    private function updateProducts($products, $check)
    {
        $newProducts=array();
        switch($check){
            case 'arts';
                $newProducts=$this->getSoap();
                break;
            case 'alts';
                foreach($this->articles as $article){
                    if($newAlts=$this->findById($article->SearchId, 'alts')){
                        foreach($newAlts as $alt){
                            $newProducts[]=$alt;
                        }
                    }
                }
                break;
            case 'notOriginal';
                foreach($this->articles as $article){
                    if($newNotOriginals=$this->findById($article->SearchId, 'notOriginal')){
                        foreach($newNotOriginals as $newNotOriginal){
                            $newProducts[]=$newNotOriginal;
                        }
                    }
                }
                break;
        }

        if($newProducts){
            $model=$this->model->load('productModel');
            foreach($products as $num=>$product){
                if(isset($newProducts[$num])){
                    $newProduct=$newProducts[$num];
                    $model->update($product->Id, array('quantity'=>$newProduct->Amount, 'stock_status_id'=>$newProduct->Duration, 'price'=>$newProduct->Cost, 'timer'=>time()));
                    $newProducts[$num]->Duration=$model->getStatusText($newProduct->Amount, $newProduct->Duration);
                    $newProducts[$num]->Id=$product->Id;
                    if($newProduct->Amount<=0) $newProducts[$num]->Amount='';
                }
            }
        }

        return $newProducts;
    }

    private function findById($id, $name)
    {
        $result=false;
        $this->params=array('id'=>$id, 'name'=>$name);
        $this->methodName='FindById';

        if($arts=$this->getSoap()){
            $n=0;
            foreach($arts as $num=>$art){
                if(!isset($arts[$n])) break;

                $id=$arts[$n]->Id;
                if($n!=$num && $id==$art->Id){
                    $n=$num+1;
                    continue;
                }

                $this->params=array('articleSearch'=>$art->Article, 'vendorSearch'=>$this->vendor);
                $this->methodName='FindAllArticles';

                if($soap=$this->getSoap()){
                    foreach($soap as $res){
                        $result[]=$res;
                    }
                }
            }
        }

        return $result;
    }

    private function getHtmlTable($products)
    {
        if(!$products) return '';

        $this->load->language('module/lekoService');

        $article=$this->language->get('article');
        $name=$this->language->get('name');
        $vendor=$this->language->get('vendor');
        $cost=$this->language->get('cost');
        $duration=$this->language->get('duration');
        $warehouse=$this->language->get('warehouse');
        $quantity=$this->language->get('quantity');
        $amount='';

        $html='<table class="articles">
            <tr class="search-table-top"><td>'.$name.'</td><td>'.$article.'</td><td>'.$cost.'</td><td>'.$quantity.'</td><td>'.$duration.'</td><td>'.$warehouse.'</td><td>'.$vendor.'</td></tr>
        ';

        foreach($products as $product){
            if($product->Amount){
                $amount=(int)$product->Amount;
                if($amount<=0) $amount='';
                elseif($amount>0 && $amount<5) $amount=$amount;
                elseif($amount>4 && $amount<11) $amount='> 4';
                elseif($amount>10 && $amount<31) $amount='> 10';
                elseif($amount>30 && $amount<51) $amount='> 30';
                elseif($amount>50 && $amount<101) $amount='> 50';
                elseif($amount>100) $amount='> 100';
            }


            $stock=isset($product->Stock) ? $product->Stock : $product->Duration;
            $availability=$this->model->load('productModel')->getStatusText($product->Amount,$stock);

            $hidden='<input class="quantity" type="hidden" name="'.$product->Id.'[amount]" value="'.$product->Amount.'" />';
            $hidden.='<input class="quantity" type="hidden" name="'.$product->Id.'[stock]" value="'.$stock.'" />';
            $html.='<tr>'.$hidden.'<td>'.$product->Name.'</td><td>'.$product->Article.'</td><td>'.$product->Cost.'</td>
                <td><input class="quantity" type="text" name="'.$product->Id.'[quantity]" value="" size="1" /></td>
                <td>'.$availability.'</td><td>'.$amount.'</td><td>'.$product->VendorName.'</td></tr>';
        }

        return $html.'</table>';
    }

    private  function getSoap()
    {
        require_once(DIR_APPLICATION.'model/leko/wsdl.php');

        $method=$this->methodName ? $this->methodName : 'FindAllArticles';
        $params=$this->params ? $this->params : array('articleSearch'=>$this->searchNum, 'vendorSearch'=>$this->vendor);

        $wsdl=new Wsdl(self::WSDL_URL, $params, array($method.'Result', 'ArticleSearchModel'));

        $result=$wsdl->$method;
        $this->error=$wsdl->errorMessage;

        if(!$result) return false;

        $result=is_array($result) ? $result : array($result);

        $vendorModel=$this->model->load('manufacturerModel');
        foreach($result as $num=>$art){
            if(is_object($art)){
                if(!isset($art->Id) || !$art->Id) return false;
                foreach($this->properties as $prop){
                    if(!isset($art->$prop)) $result[$num]->$prop='';
                }
                $result[$num]->SearchId=$art->Id;
                if(!$vendorModel->findByAttributes(array('name'=>$art->VendorName))) $vendorModel->save(array('name'=>$art->VendorName, 'image'=>'', 'sort_order'=>0));
            }
        }

        if(sizeof($result==1) && !$result[0]) return false;

        return $result;
    }

    /*
    public function webServiceMysqlTest($id)
    {
        $method='GetCustomerRetailInfo';
        $params=array(
            'orderId'=>$id,
        );

        require_once(DIR_APPLICATION.'model/leko/wsdl.php');

        $wsdl=new Wsdl(self::WSDL_URL, $params, array($method.'Result'));
        //$wsdl=new Wsdl(self::WSDL_URL, $params, array($method.'Result', 'ArticleSearchModel'));

        $result=$wsdl->$method;
        $error=$wsdl->errorMessage;

        return array(
            'result'=>$result,
            'error'=>$error,
        );
    }
    */
}